package com.sharkburner.aeris.servlet;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.sharkburner.aeris.bean.UserBean;
import com.sharkburner.aeris.service.user.impl.UserServiceImpl;

/**
 * Servlet implementation class CreateAccountServlet
 */
@Component
@Scope("request")
public class CreateAccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserBean userBean = new UserBean();
	@Autowired
	private UserServiceImpl userService;
	private ClassPathXmlApplicationContext appContext;
	private BeanFactory factory;

	@PostConstruct
	public void init() {
		appContext = new ClassPathXmlApplicationContext(new String[] { "springContext.xml" });
		factory =  (BeanFactory) appContext;
		userService = (UserServiceImpl) factory.getBean("userService");
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		goForward(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		execute(request, response);
	}

	/**
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println(">>> Page 'Create Account' submit!");

		userBean.setEmail(request.getParameter("email"));
		userBean.setPassword(request.getParameter("password"));
		userService.save(userBean);

		goForward(request, response);
	}

	/**
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void goForward(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		getServletConfig().getServletContext()
				.getRequestDispatcher("/create-account.jsp")
				.forward(request, response);

	}

}
